package net.ujacha.bethany.conv;

import java.io.File;
import java.io.PrintStream;
import java.text.SimpleDateFormat;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.SystemUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Main {

	private final static Logger LOGGER = LoggerFactory.getLogger(Main.class);

	private static final String MDB_DIR = "C:/Users/shkim/Desktop/mdb";
	private static final String SAVE_DIR = "C:/Users/shkim/Desktop/save";

	public static void main(String[] args) {

		int recordCount = 0;

		SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd", Locale.US);

		File mdbDir = new File(MDB_DIR);
		File saveDir = new File(SAVE_DIR);

		if (!saveDir.isDirectory()) {
			saveDir.mkdirs();
		}

		Iterator<File> mdbs = FileUtils.iterateFiles(mdbDir,
				new String[] { "mdb" }, true);

		BethanyMdbConverter converter = new BethanyMdbConverter();

		while (mdbs.hasNext()) {
			File mdb = mdbs.next();
			LOGGER.debug("File : {}", mdb.getAbsoluteFile());

			String fileName = mdb.getName();

			List<BethanyModel> list = null;

			try {
				list = converter.conv(mdb);
			} catch (Exception e) {
				LOGGER.error("{} : {}", e.getMessage(), fileName);
			}

			if (list != null && list.size() > 0) {

				PrintStream ps = null;

				try {

					ps = new PrintStream(new File(saveDir,
							FilenameUtils.getBaseName(fileName) + ".txt"));

					for (BethanyModel b : list) {

						StringBuffer sb = new StringBuffer();

						sb.append("id=").append(b.getId()).append("\t")
								.append("category=").append(b.getCategory())
								.append("\t").append("writeDate=")
								.append(format.format(b.getWriteDate()))
								.append(SystemUtils.LINE_SEPARATOR);

						sb.append("").append(b.getTitle())
								.append(SystemUtils.LINE_SEPARATOR);

						sb.append(b.getContent()).append(
								SystemUtils.LINE_SEPARATOR);

						sb.append(
								"================================================================================")
								.append(SystemUtils.LINE_SEPARATOR);

						ps.print(sb.toString());

						recordCount++;

					}

				} catch (Exception e) {
					LOGGER.error(e.getMessage());
				} finally {
					IOUtils.closeQuietly(ps);
				}

			} else {

				LOGGER.info("{} is empty...", fileName);

			}

		}

		LOGGER.info("Convert {} records", recordCount);

	}
}
